<template>
  <el-upload
    :class="hideUpload ? 'hide' : 'show'"
    v-model:file-list="fileList"
    action="/api/system/file/upload/webFile"
    :headers="{ WXToken: tokenStore().token, client: 'WEB_USER' }"
    :before-upload="handleBeforeUpload"
    :on-success="handleAvatarSuccess"
    :on-remove="handleRemove"
    :show-file-list="true"
    multiple
  >
    <el-button size="large"><img src="../assets/static/upload.png" width="25" /></el-button>
  </el-upload>
</template>

<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { tokenStore } from '@/store/token'
import { ElMessage } from 'element-plus/es'
const fileList = ref<UploadUserFile[]>([])
const hideUpload = ref(false)
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {}
let props = defineProps({ file_url: { default: null }, file_max: { type: Number, default: 1 } })
const emit = defineEmits(['update:file_url', 'update:file_max'])
const fileType = ref(['doc', 'xls', 'ppt', 'txt', 'pdf', 'mp4', 'mp3'])
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (file.type) {
    let fileExtension = ''
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
    }
    const isTypeOk = fileType.value.some(type => {
      return fileExtension && fileExtension.indexOf(type) > -1
    })
    if (!isTypeOk) {
      const types = fileType.value.join('/')
      ElMessage({
        message: '文件格式不正确，请上传' + types + '格式文件！',
        type: 'error'
      })
      return false
    }
    if (file.size / 1024 / 1024 > 100) {
      ElMessage({
        message: '上传文件大小不能超过100 M!',
        type: 'error'
      })
      return false
    }
    return true
  } else {
    ElMessage({
      message: '请上传正确格式的的文件',
      type: 'error'
    })
    return false
  }
}

//上传成功
const handleAvatarSuccess = (response, uploadFile) => {
  let urls = []
  if (fileList.value) {
    urls = fileList.value.filter(s => s.url).map(ss => ss.url)
    const responseUrl = fileList.value.filter(s => s.response && s.response.data && s.response.data !== response.data).map(ss => ss.response.data)
    if (responseUrl && responseUrl.length > 0) {
      urls = urls.concat(responseUrl)
    }
  }
  if (response.data) {
    urls.push(response.data)
  }
  if (urls && urls.length > 0) {
    emit('update:file_url', urls)
  }
  hideUpload.value = urls.length >= props.file_max
}
// 删除文件
const handleRemove = (file: any) => {
  const urls = fileList.value.filter(s => s.url !== file.url).map(ss => ss.url)
  emit('update:file_url', urls)
  hideUpload.value = urls.length >= props.file_max
}
//进页面加载图片
const loadData = () => {
  if (!props.file_url) {
    return
  }
  fileList.value = []
  //判断是否之穿一个
  if (props.file_max === 1) {
    const dir = props.file_url.split('/')
    fileList.value?.push({
      name: dir[dir.length - 1],
      url: props.file_url
    })
  } else {
    if (props.file_url) {
      const fileUrls = props.file_url
      if (!fileUrls || fileUrls.length == 0) {
        return
      }
      if (fileUrls instanceof Array) {
        fileUrls.forEach((ss: string) => {
          if (!ss) {
            return
          }
          const dir = ss.split('/')
          fileList.value?.push({
            name: dir[dir.length - 1],
            url: ss.valueOf()
          })
        })
      }
    }
  }
  hideUpload.value = fileList.value.length >= props.file_max
}
// 加载图片
onMounted(async () => {
  loadData()
})
</script>
<style lang="scss" scoped>
.hide {
  position: relative;
  float: left;
  padding-top: 20px;
  padding-left: 23px;
  :deep(.el-upload--text) {
    display: none;
    .el-upload-list__item {
      border: 0;
      border-radius: 0;
      margin: 0 30px 0 0;
    }
  }
}
</style>
